<template>
    <div>
        <div>浏览器录音听写：<button id="btn_control" @click="handleButtonClick">{{ btnText }}</button></div>
        <div id="result"></div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import CryptoJS from 'crypto-js';

// 引用全局变量
const APPID = window.APPID;
const API_KEY = window.API_KEY;

let iatWS;
let resultText = '';
let resultTextTemp = '';

// 状态管理
const btnStatus = ref('UNDEFINED');
const btnText = computed(() => {
    return btnStatus.value === 'CLOSED' ? '开始录音' : '停止录音';
});

function getWebSocketUrl() {
    const url = "ws://rtasr.xfyun.cn/v1/ws";
    const ts = Math.floor(new Date().getTime() / 1000);
    const signa = CryptoJS.MD5(APPID + ts).toString();
    const signatureSha = CryptoJS.HmacSHA1(signa, API_KEY);
    const signature = encodeURIComponent(CryptoJS.enc.Base64.stringify(signatureSha));
    return `${url}?appid=${APPID}&ts=${ts}&signa=${signature}`;
}

function changeBtnStatus(status) {
    btnStatus.value = status;
    if (status === "CONNECTING") {
        document.getElementById("btn_control").innerText = "建立连接中";
        document.getElementById("result").innerText = "";
        resultText = "";
        resultTextTemp = "";
    } else if (status === "OPEN") {
        document.getElementById("btn_control").innerText = "录音中";
    } else if (status === "CLOSING") {
        document.getElementById("btn_control").innerText = "关闭连接中";
    } else if (status === "CLOSED") {
        document.getElementById("btn_control").innerText = "开始录音";
    }
}

function renderResult(resultData) {
    let jsonData = JSON.parse(resultData);
    if (jsonData.action == "started") {
        console.log("握手成功");
    } else if (jsonData.action == "result") {
        const data = JSON.parse(jsonData.data);
        console.log(data);
        resultTextTemp = "";
        data.cn.st.rt.forEach((j) => {
            j.ws.forEach((k) => {
                k.cw.forEach((l) => {
                    resultTextTemp += l.w;
                });
            });
        });
        if (data.cn.st.type == 0) {
            resultText += resultTextTemp;
            resultTextTemp = "";
        }
        document.getElementById("result").innerText = resultText + resultTextTemp;
    } else if (jsonData.action == "error") {
        console.log("出错了:", jsonData);
    }
}

function connectWebSocket() {
    const websocketUrl = getWebSocketUrl();
    console.log("websocketUrl:", websocketUrl);
    if ("WebSocket" in window) {
        iatWS = new WebSocket(websocketUrl);
    } else if ("MozWebSocket" in window) {
        iatWS = new MozWebSocket(websocketUrl);
    } else {
        alert("浏览器不支持WebSocket");
        return;
    }
    changeBtnStatus("CONNECTING");
    iatWS.onopen = (e) => {
        console.log("WebSocket connection opened:", e);
        if (typeof navigator !== 'undefined' && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            recorder.start({
                sampleRate: 16000,
                frameSize: 1280,
            }).then(() => {
                console.log("录音开始成功");
            }).catch((error) => {
                console.error("录音开始失败:", error);
            });
        } else {
            console.error("浏览器不支持录音功能");
        }
    };
    iatWS.onmessage = (e) => {
        renderResult(e.data);
    };
    iatWS.onerror = (e) => {
        console.error(e);
        recorder.stop();
        changeBtnStatus("CLOSED");
    };
    iatWS.onclose = (e) => {
        recorder.stop();
        changeBtnStatus("CLOSED");
    };
}

const recorder = new RecorderManager('/static/dist');
recorder.onStart = () => {
    changeBtnStatus("OPEN");
};
recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
    if (iatWS.readyState === WebSocket.OPEN) {
        iatWS.send(new Int8Array(frameBuffer));
        if (isLastFrame) {
            iatWS.send('{"end": true}');
            changeBtnStatus("CLOSING");
        }
    }
};
recorder.onStop = () => {
    // 停止录音后的清理工作
};

function handleButtonClick() {
    if (btnStatus.value === 'UNDEFINED' || btnStatus.value === 'CLOSED') {
        connectWebSocket();
    } else if (btnStatus.value === 'CONNECTING' || btnStatus.value === 'OPEN') {
        recorder.stop();
    }
}

onMounted(() => {
    // 初始化操作可以放在这里
});
</script>

<style scoped>
/* 你的样式 */
</style>